#import "UserManager.h"
#import <UMSocialCore/UMSocialCore.h>
#import <UMPush/UMessage.h>
#import "LoginModel.h"
@implementation UserManager
SINGLETON_FOR_CLASS(UserManager);
-(instancetype)init{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(onKick)
                                                     name:KNotificationOnKick
                                                   object:nil];
    }
    return self;
}
#pragma mark ————— 三方登录 —————
-(void)login:(UserLoginType )loginType completion:(loginBlock)completion{
    [self login:loginType params:nil completion:completion];
}
#pragma mark ————— 带参数登录 —————
-(void)login:(UserLoginType )loginType params:(NSDictionary *)params completion:(loginBlock)completion{
    [UMSocialGlobal shareInstance].isClearCacheWhenGetUserInfo = YES;
    UMSocialPlatformType platFormType;
    if (loginType == kUserLoginTypeQQ) {
        platFormType = UMSocialPlatformType_QQ;
    }else if (loginType == kUserLoginTypeWeChat){
        platFormType = UMSocialPlatformType_WechatSession;
    }else{
        platFormType = UMSocialPlatformType_UnKnown;
    }
    if ((loginType != kUserLoginTypePwd) && (loginType != OmUserLoginTypeNormal) && (loginType != OmUserLoginTypeRegister)) {
        [MBProgressHUD showActivityMessageInView:ASLocalizedString(@"授权中...")];
        [[UMSocialManager defaultManager] getUserInfoWithPlatform:platFormType currentViewController:nil completion:^(id result, NSError *error) {
            if (error) {
                [MBProgressHUD hideHUD];
                if (completion) {
                    completion(NO,error.localizedDescription);
                }
            } else {
                [MBProgressHUD hideHUD];
                UMSocialUserInfoResponse *resp = result;
                self.loginType = loginType;
                [self loginToServerWidthOpenID:resp.openid completion:completion];
            }
        }];
    } else {
        if (loginType == OmUserLoginTypeNormal) {
            [self OmLogin:params completion:^(BOOL success, NSString *des) {
                completion(success, des);
            }];
        } else if (loginType == OmUserLoginTypeRegister) {
            [self OmRegister:params completion:^(BOOL success, NSString *des) {
                completion(success, des);
            }];
        } else {
            [self loginToServer:params completion:^(BOOL success, NSString *des) {
                completion(success,des);
            }];
        }
    }
}
#pragma mark - 第三方登录
-(void)loginToServerWidthOpenID:(NSString *)openid completion:(loginBlock)completion{
    [[HUDHelper sharedInstance] syncLoading:ASLocalizedString(@"登录中...")];
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"login_api" A:@"auth_login"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:openid forKey:@"plat_id"];
    [param setObject:[LoginModel sharedLoginModel].invite_code forKey:@"invite_code"];
    [CYNET POSTv3:url parameters:param responseCache:^(id responseObject) {
    } success:^(id responseObject) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [MBProgressHUD hideHUD];
        [self LoginSuccess:[responseObject valueForKey:@"data"] completion:completion];
    } failure:^(NSString *error, NSInteger code) {
    } hasCache:NO];
}
#pragma mark ————— 手动登录到服务器 —————
-(void)loginToServer:(NSDictionary *)params completion:(loginBlock)completion{
        NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"login_api" A:@"do_login"];
        [CYNET POST:url parameters:params responseCache:^(id responseObject) {
        } success:^(id responseObject) {
            [MBProgressHUD hideHUD];
            [self LoginSuccess:responseObject completion:completion];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [UMessage registerDeviceToken:LoadObjFromUserDefault(OmDeviceTokenKey)];
                [UMessage setAlias:curUser.id  type:@"buguniao" response:^(id  _Nullable responseObject, NSError * _Nullable error) {
                    NSLog(ASLocalizedString(@"绑定别名%@===%@"),responseObject,error);
                }];
            });
            NSString *Furl = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"user_api" A:@"is_agency"];
            NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
            [CYNET POST:Furl parameters:parameters responseCache:nil success:^(id responseObject) {
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"DaiLiQuanXian"];
            } failure:^(NSString *error) {
                [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"DaiLiQuanXian"];
            } hasCache:NO];
        } failure:^(NSString *error) {
            [[HUDHelper sharedInstance] syncStopLoading];
            completion(NO,error);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [MBProgressHUD showInfoMessage:error];
            });
        } hasCache:NO];
}
-(void)OmLogin:(NSDictionary *)params completion:(loginBlock)completion{
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"login_api" A:@"login"];
    [CYNET POST:url parameters:params responseCache:^(id responseObject) {
    } success:^(id responseObject) {
        [MBProgressHUD hideHUD];
        [self LoginSuccess:responseObject completion:completion];
        NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"user_api" A:@"update_user_lang"];
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        parameters[@"lang"] = isCurrentLanguageChinese ? @(2) : @(1);
        [CYNET POST:url parameters:parameters responseCache:^(id responseObject) {
        } success:^(id responseObject) {
        } failure:^(NSString *error) {
        } hasCache:NO];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UMessage registerDeviceToken:LoadObjFromUserDefault(OmDeviceTokenKey)];
            [UMessage setAlias:curUser.id  type:@"buguniao" response:^(id  _Nullable responseObject, NSError * _Nullable error) {
                NSLog(ASLocalizedString(@"绑定别名%@===%@"),responseObject,error);
            }];
        });
        NSString *Furl = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"user_api" A:@"is_agency"];
        NSMutableDictionary *pparameters = [NSMutableDictionary dictionary];
        [CYNET POST:Furl parameters:pparameters responseCache:nil success:^(id responseObject) {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"DaiLiQuanXian"];
        } failure:^(NSString *error) {
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"DaiLiQuanXian"];
        } hasCache:NO];
    } failure:^(NSString *error) {
        [[HUDHelper sharedInstance] syncStopLoading];
        completion(NO,error);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD showInfoMessage:error];
        });
    } hasCache:NO];
}
-(void)OmRegister:(NSDictionary *)params completion:(loginBlock)completion{
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"login_api" A:@"register"];
    [CYNET POST:url parameters:params responseCache:^(id responseObject) {
    } success:^(id responseObject) {
        [MBProgressHUD hideHUD];
        [self LoginSuccess:responseObject completion:completion];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UMessage registerDeviceToken:LoadObjFromUserDefault(OmDeviceTokenKey)];
            [UMessage setAlias:curUser.id  type:@"buguniao" response:^(id  _Nullable responseObject, NSError * _Nullable error) {
                NSLog(ASLocalizedString(@"绑定别名%@===%@"),responseObject,error);
            }];
        });
        NSString *Furl = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"user_api" A:@"is_agency"];
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [CYNET POST:Furl parameters:parameters responseCache:nil success:^(id responseObject) {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"DaiLiQuanXian"];
        } failure:^(NSString *error) {
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"DaiLiQuanXian"];
        } hasCache:NO];
    } failure:^(NSString *error) {
        [[HUDHelper sharedInstance] syncStopLoading];
        completion(NO,error);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD showInfoMessage:error];
        });
    } hasCache:NO];
}
#pragma mark ————— 自动登录到服务器 —————
-(void)autoLoginToServer:(loginBlock)completion{    
}
#pragma mark ————— 登录成功处理 —————
-(void)LoginSuccess:(id )responseObject completion:(loginBlock)completion{
    [UserManager sharedUserManager].curUserInfo = [UserInfo modelWithDictionary:responseObject];
    [[IMManager sharedIMManager] IMLogin:@"" IMPwd:@"" completion:^(BOOL success, NSString *des) {
        [MBProgressHUD hideHUD];
        if (success) {
            self.isLogined = YES;
            [[UserManager sharedUserManager] saveUserInfo];
            if (completion) {
                completion(YES,nil);
            }
        }else{
            if (completion) {
                [[IMManager sharedIMManager] IMLogin:@"" IMPwd:@"" completion:^(BOOL success, NSString *des) {
                    [MBProgressHUD hideHUD];
                    if (success) {
                        self.isLogined = YES;
                        [[UserManager sharedUserManager] saveUserInfo];
                        if (completion) {
                            completion(YES,nil);
                        }
                    }else{
                        if (completion) {
                            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ASLocalizedString(@"IM登录超时")message:des
                                                                           delegate:nil
                                                                  cancelButtonTitle:ASLocalizedString(@"重新登录")otherButtonTitles:nil];
                            [alert show];
                            completion(NO,ASLocalizedString(@"IM登录失败"));
                        }
                        KPostNotification(KNotificationLoginStateChange, @NO);
                    }
                }];
            }
            KPostNotification(KNotificationLoginStateChange, @NO);
        }
    }];
}
#pragma mark ————— 储存用户信息 —————
-(void)saveUserInfo{
    if (self.curUserInfo) {
        NSDictionary *dic = [self.curUserInfo modelToJSONObject];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:dic forKey:@"cyUsefInfo"];
        [defaults synchronize];
    }
}
#pragma mark ————— 加载缓存的用户信息 —————
-(BOOL)loadUserInfo{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *userinfo = [defaults objectForKey:@"cyUsefInfo"];
    if(userinfo)
    {
        self.curUserInfo = [UserInfo modelWithJSON:userinfo];
        return YES;
    }
    return NO;
    return NO;
}
#pragma mark ————— 被踢下线 —————
-(void)onKick{
    [self logout:nil];
}
#pragma mark ————— 退出登录 —————
- (void)logout:(void (^)(BOOL, NSString *))completion{
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [[UIApplication sharedApplication] unregisterForRemoteNotifications];
    [[IMManager sharedIMManager] IMLogout];
    self.curUserInfo = nil;
    self.isLogined = NO;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:@"cyUsefInfo"];
    [defaults synchronize];
    KPostNotification(KNotificationLoginStateChange, @NO);
}
@end
